package com.loadburn.heron.complier.tags;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.mvel2.MVEL;
import org.mvel2.ParserContext;
import org.mvel2.integration.VariableResolverFactory;
import org.mvel2.templates.TemplateRuntime;
import org.mvel2.templates.util.TemplateOutputStream;
import org.mvel2.util.ParseTools;

import java.io.Serializable;

/**
 * @author slacrey (scstlinfeng@yahoo.com)
 *         Date: 13-12-26
 */
public class CompiledHasAnyPermissionNode extends HasAnyPermissionNode {

    private static final long serialVersionUID = 5917900740410099062L;
    private Serializable ce;

    public CompiledHasAnyPermissionNode(int begin, String name, char[] template, int start, int end, ParserContext context) {
        super(begin, name, template, start, end);
        while (cEnd > cStart && ParseTools.isWhitespace(template[cEnd])) cEnd--;
        if (cStart != cEnd) {
            ce = MVEL.compileExpression(template, cStart, cEnd - start, context);
        }
    }

    public Object eval(TemplateRuntime runtime, TemplateOutputStream appender, Object ctx, VariableResolverFactory factory) {

        boolean hasAnyPermission = false;
        Subject subject = SecurityUtils.getSubject();
        if (subject != null) {
            String permissionNames = MVEL.executeExpression(ce, ctx, factory, String.class);
            for (String permission : permissionNames.split(PERMISSION_NAMES_SPLIT)) {
                if (subject.isPermitted(permission.trim())) {
                    hasAnyPermission = true;
                    break;
                }
            }
        }
        if (ce == null || hasAnyPermission) {
            return trueNode.eval(runtime, appender, ctx, factory);
        }

        return next != null ? next.eval(runtime, appender, ctx, factory) : null;
    }

}
